import axios from "axios";
import store from "@/store/store.js";
import qs from "qs";
import { Message } from 'element-ui';

const baseURL = process.env.VUE_APP_BASE_API;

const instance = axios.create({
    baseURL: baseURL,
    timeout: 5000,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': '*/*'
    }
})

instance.interceptors.request.use(
    (config) => {
        config.headers["token"] = (store.state.token || "");
        config.data = qs.stringify(config.data)
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

instance.interceptors.response.use(
    (response) => {
        if (response.status == 200) {
            if (response.data.code == 1) {
                return response.data;
            }else {
                Message.error({ message: response.data.msg });
                return response.data;
            }
        }
        return response;
    },
    (error) => {
        console.log(error);
        if (error.response.data.code == 401) {
            store.commit("LOGIN_OUT");
            return null;
        }
        if (error.response.status == 500) {
            Message.error({ message: "net error" });
        }
        return Promise.reject(error);
    }
);

export function get(url, data) {
    return instance.get(baseURL + url, { data: data });
}

export function post(url, data) {
    return instance.post(baseURL + url, data);
}

export function upFile(url, file) {
    const fileData = new FormData();
    fileData.append('file', file, '1.png');
    return axios.post(baseURL + url, fileData, {
        headers: {
            "token": (store.state.token || ""),
            "Content-Type": 'multipart/form-data',
        },
    });
}

export default {
    get,
    post,
    baseURL,
    upFile
};